<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">团队奖</p>
      </div>
      <!-- 搜索 -->
      <div class="g-search" style="padding-top: 0" ref="searchBox">
        <!-- 顶部按钮区域 -->
        <!-- <div class="function_Btn" style="margin-bottom: 10px">
              <el-button class="hollow" @click="exportExcel"
                >导出商品信息</el-button
              >
            </div> -->
        <!-- 时间选择区域 -->
        <div class="search_box1">
          <div class="demo-date-picker">
            <div class="block">
              <span class="demonstration" @change="startTime">创建时间：</span>
              <el-date-picker
                v-model="searchValue.beginTime"
                type="date"
                placeholder="开始时间"
                @change="startTime"
                :clearable="false"
                :default-time="defaultTime(0, 0, 0)" />

              <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
                >至</span
              >
              <el-date-picker
                v-model="searchValue.endTime"
                type="date"
                placeholder="结束时间"
                @change="endTime"
                :clearable="false"
                :default-time="defaultTime1(23, 59, 59)" />
            </div>
          </div>
          &emsp;
          <!-- 信息区域 -->
          <div class="all_select">
            <!-- 用户名 -->
            <div class="input_valye" style="margin-bottom: 0">
              <span class="demonstration">用户名：</span>
              <input
                type="text"
                class="input"
                placeholder="请输入用户名"
                v-model="searchValue.name"
                style="width: 180px" />
            </div>

            <!-- 入账状态 -->
            <div class="input_valye" style="margin-bottom: 0">
              <span class="demonstration">入账状态：</span>
              <el-select v-model="searchValue.checked" class="m-2" placeholder="请选择入账状态" style="width: 180px">
                <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 表格按钮区域 -->
        <div class="table_function" v-if="roleList.write">
          <el-button class="solid" @click="allSettlement">批量处理</el-button>
          <el-button class="hollow" @click="exportExcelList">导出明细</el-button>
        </div>
        <!-- 表格区域 -->
        <el-table
          id="out-table"
          :data="tableData"
          :row-class-name="tableRowClassName"
          @select-all="handleSelectionChange"
          @select="handleSelectionChange"
          :header-cell-style="{'text-align': 'center'}"
          :show-overflow-tooltip="true"
          v-adaptive
          border>
          <el-table-column type="selection" width="40" />
          <el-table-column prop="userPhone" label="团队奖账号" align="center" />
          <el-table-column prop="username" label="账号名称" align="center" />
          <el-table-column prop="origin" label="获取来源" align="center">
            <template #default="item">
              <span v-if="item.row.origin == 't'">报废</span>
              <span v-else>商城</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderSn" label="订单号" align="center" />
          <el-table-column prop="amount" label="分账金额" align="center" />
          <el-table-column prop="checked" label="入账状态" align="center">
            <template #default="item">
              <span v-if="item.row.checked">已入账</span>
              <span v-else>未入账</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="180" align="center" />
          <el-table-column prop="updatedAt" label="结算时间" width="180" align="center">
            <template #default="item">
              <span v-if="item.row.checked">{{ item.row.updatedAt }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" class="operation">
            <template #default="item" v-if="roleList.write">
              <div class="table_btn">
                <el-button size="small" v-if="!item.row.checked" class="none" @click="settlement(item.row.id)"
                  >确认结算
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="total"
          @change="pageChange" />
      </div>
      <div id="mask1" v-if="mask" @click="maskBtn1"></div>
      <!-- 点击结算 -->
      <div class="plateform" v-if="mask">
        <div class="title1">
          <div class="title_mes">
            <el-icon size="20" color="#fff"> <Edit /> </el-icon>&nbsp;团队奖结算
          </div>
          <span class="close" @click="maskBtn1">✖</span>
        </div>
        <div class="content1">
          <span class="center_text"
            >共
            <span style="color: #f56c6c">{{ producIds.length }}</span> 条未结算记录，确定将所选内容进行批量结算？</span
          >
          <div class="btn_center">
            <el-button class="hollow" @click="maskBtn1">取消</el-button>
            <el-button class="solid" @click="settlementSure">确定</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import moment from 'moment';
import {RequestPersonalRecords, RequesTextractToLeftMoney} from '@/api/path/index.js';
import useAuthorize from '@/hooks/authorize';
import {Edit} from '@element-plus/icons-vue';
/**
 * 挂载
 */
onMounted(async () => {
  requestPersonalRecords();
  handleResize();
  window.addEventListener('resize', handleResize);
});
let roleList = useAuthorize();
/*************************************************************  搜索栏  *************************************************************/
const shopId = Number(localStorage.getItem('ShopId'));
// 搜索参数
const searchValue = ref({
  beginTime: '',
  endTime: '',
  name: '',
  originType: '3',
  checked: '',
  page: 1,
  rows: 10,
});
// 状态选择器
const status_options = [
  {
    value: false,
    label: '未入账',
  },
  {
    value: true,
    label: '已入账',
  },
];
/**
 * 时间处理
 */
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
const defaultTime1 = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
// 开始时间
const startTime = () => {
  searchValue.value.beginTime.setHours(0);
  searchValue.value.beginTime.setMinutes(0);
  searchValue.value.beginTime.setSeconds(0);
  searchValue.value.beginTime = moment(searchValue.value.beginTime);
};
// 结束时间
const endTime = () => {
  searchValue.value.endTime.setHours(23);
  searchValue.value.endTime.setMinutes(59);
  searchValue.value.endTime.setSeconds(59);
  searchValue.value.endTime = moment(searchValue.value.endTime);
};
/**
 * 搜索点击
 */
const search = () => {
  searchValue.value.page = 1;
  console.log('searchValue.value', searchValue.value);
  requestPersonalRecords();
};
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    beginTime: '',
    endTime: '',
    name: '',
    originType: '3',
    checked: '',
    page: 1,
    rows: 10,
  };
  requestPersonalRecords();
};
/**
 * 获取搜索盒子的高度
 */
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
};
/*************************************************************  表格相关  *************************************************************/
/**
 * 表格相关数据，事件
 */
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数
// 获取表格列表
const requestPersonalRecords = async () => {
  const a = await RequestPersonalRecords(searchValue.value);
  if (a.msg == '操作成功！') {
    tableData.value = a.resultObj.data;
    total.value = a.resultObj.total;
  }
};
// 表格颜色区分
const tableRowClassName = ({row, rowIndex}: any) => {
  if (rowIndex % 2 !== 0 || row.selection === true) {
    if (row.selection === true) {
      return 'check_table';
    } else {
      return 'warning-row';
    }
  } else {
    return '';
  }
};
const teamList = ref([]);
// 表格多选事件
const handleSelectionChange = (selection: any, row: any) => {
  teamList.value = selection;
};
/**
 * 批量结算
 */
const producIds = ref<any>([]);
const isTrue = ref(false);
const allSettlement = () => {
  if (teamList.value.length <= 0) {
    ElMessage.error('请选择要结算的数据');
  } else {
    producIds.value = [];
    isTrue.value = false;
    for (let i = 0; i < teamList.value.length; i++) {
      if (teamList.value[i].checked) {
        isTrue.value = true;
        ElMessage.error('已结算的不能再次结算！');
        break;
      } else {
        producIds.value.push(teamList.value[i].id);
        console.log('结算id', producIds.value);
      }
    }
    if (!isTrue.value) {
      mask.value = true;
    }
  }
};
/**
 * 点击结算
 */
const settlement = (id: Number) => {
  producIds.value = [id];
  mask.value = true;
};
/**
 * 确认结算
 */
const settlementSure = async () => {
  const a = await RequesTextractToLeftMoney(producIds.value.join(','));
  if (a.msg == '操作成功！') {
    maskBtn1();
    ElMessage.success('结算成功');
  } else {
    ElMessage.error('结算失败，请重试！');
  }
};
/**
 * 分页
 */
const pageChange = async (val: Number) => {
  requestPersonalRecords();
};
const mask = ref(false);
/**
 * 遮罩层数据，事件
 */
const maskBtn1 = () => {
  mask.value = false;
  requestPersonalRecords();
};
/**
 * 导出信息
 */
const exportBox = ref([]);
const exportExcelList = async () => {
  exportBox.value = [];
  const a = await RequestPersonalRecords({
    beginTime: searchValue.value.beginTime,
    endTime: searchValue.value.endTime,
    name: searchValue.value.name,
    originType: '3',
    checked: searchValue.value.checked,
  });
  if (a.msg == '操作成功！') {
    exportBox.value = a.resultObj.data;
    const titleArr = ['账号', '用户名', '来源', '订单号', '分账金额(元)', '入账状态', '创建时间', '结算时间']; //表头中文名
    const contentArr = ['userPhone', 'username', 'origin', 'orderSn', 'amount', 'checked', 'createdAt', 'updatedAt']; //表头中文名
    exportExcel(exportBox.value, titleArr, contentArr, '团队奖');
  } else {
    ElMessage.error('导出失败！请重试！');
  }
};
import * as XLSX from 'xlsx';
const getLength = function (obj: any) {
  var count = 0;
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      count++;
    }
  }
  return count;
};
const exportExcel = (json: any, titleArr: any, contentArr: any, execlName: String) => {
  var data = new Array();
  var keyArray = new Array();
  // 获取数组的length
  for (const key1 in json) {
    if (json.hasOwnProperty(key1)) {
      const element = json[key1];
      var rowDataArray = new Array();
      for (let i = 0; i < contentArr.length; i++) {
        console.log('zzzzzzzzzzz', element['amount']);

        if (i == 2) {
          rowDataArray[i] = element[contentArr[i]] == 't' ? '报废' : '商城';
        } else if (i == 5) {
          rowDataArray[i] = element[contentArr[i]] == true ? '已入账' : '未入账';
        } else if (i == 7) {
          rowDataArray[i] = element['checked'] == true ? element[contentArr[i]] : '--';
        } else {
          rowDataArray[i] = element[contentArr[i]];
        }
      }
      for (const key2 in element) {
        if (keyArray.length < getLength(element)) {
          keyArray.push(key2);
        }
      }
      data.push(rowDataArray);
    }
  }
  data.splice(0, 0, keyArray, titleArr);
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  var wsrows = [{hidden: true}];
  ws['!rows'] = wsrows;
  XLSX.utils.book_append_sheet(wb, ws, 'sheetName');
  XLSX.writeFile(wb, moment(new Date()).format('yyyy-MM-DD HH/mm/ss') + execlName + '.xlsx');
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

.g-container {
  align-content: flex-start;
  flex-direction: column;
}

.table {
  padding: 0 12px 12px;
  height: calc(100% - v-bind(tablelistHeight)) !important;
}
/**
 * 结算页面
 */
.plateform {
  width: 600px;
  height: 200px;
  position: absolute;
  background: #fff;
  z-index: 9999;
  top: 25%;
  left: 50%;
  margin-left: -300px;
  .center_text {
    font-size: 14px;
    color: #9e9e9e;
    line-height: 70px;
  }
}

::v-deep .el-table--fit {
  height: calc(100% - 120px) !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}

.el-select {
  width: 224px;
}

::v-deep .el-select {
  position: relative;
  border-color: red;
}

::v-deep .el-table {
  flex: 1 !important;
  flex-direction: column;
  display: flex;
}

::v-deep .el-table__inner-wrapper {
  flex: 1 !important;
}

::deep(.el-table) {
  flex: 1 !important;
}

::deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  z-index: initial !important;
}

::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
  z-index: initial !important;
}
::v-deep .el-table .cell {
  white-space: nowrap !important;
}
</style>
